<script setup>
import { reactive, ref, defineEmits } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElNotification } from 'element-plus'

const { t } = useI18n()
const emits = defineEmits(['sendSearchOptions'])

const option = reactive({
  query: '',
  searchType: '',
})

const isComposing = ref(false)

const handleCompositionStart = () => {
  isComposing.value = true
}

const handleCompositionEnd = () => {
  isComposing.value = false
  handleQueryChange()
}

const handleQueryChange = () => {
  if (isComposing.value) return

  // 判断是否为纯数字
  if (/^[Ee]\d+$/.test(option.query)) {
    option.searchType = 'idCard'
  } else {
    option.searchType = 'name'
  }
}

const handleSearch = () => {
  if (!option.query.trim()) {
    ElNotification({
      title: t('tips'),
      message: t('pleaseEnterSearchContent'),
      type: 'warning'
    })
    return
  }
  emits('sendSearchOptions', option)
}
</script>

<template>
  <div class="filter-container">
    <div class="search-box">
      <el-input
        v-model="option.query"
        :placeholder="$t('searchPlaceholder')"
        @input="handleQueryChange"
        @compositionstart="handleCompositionStart"
        @compositionend="handleCompositionEnd"
        clearable
      >
        <template #append>
          <el-button @click="handleSearch">{{ $t('search') }}</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<style scoped>
.search-container {
  display: flex;
  align-items: center;
  justify-content: flex-end; /* 修改为右对齐 */
  gap: 10px;
  padding-top: 1px;
  padding-bottom: 5px;
}

.search-input {
  width: 300px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  padding: 10px;
  font-size: 14px;
}

.search-button,
.reset-button {
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  font-size: 14px;
}

.search-button {
  background-color: #409eff;
  color: white;
}

.reset-button {
  background-color: #f4f4f4;
  color: #409eff;
  border: 1px solid #409eff;
}

.search-button:hover,
.reset-button:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.search-button:active,
.reset-button:active {
  transform: scale(0.98);
}

.reset-button:hover {
  background-color: #e6f7ff;
}

.search-input .el-input__inner {
  font-size: 14px;
}
</style>
